/**
 * 封装 fetch 请求，自动添加 JWT 令牌
 */

// 创建请求实例
const request = async (url, options = {}) => {
  // 设置默认headers
  const headers = options.headers || {}
  
  // 获取访问令牌
  const accessToken = localStorage.getItem('access_token')
  
  // 如果有令牌，添加到Authorization请求头
  if (accessToken) {
    headers.Authorization = `Bearer ${accessToken}`
  }
  
  // 合并选项
  const config = {
    ...options,
    headers: {
      'Content-Type': 'application/json',
      ...headers
    }
  }
  
  try {
    const response = await fetch(url, config)
    
    // 如果返回401（未授权），可能是令牌过期
    if (response.status === 401) {
      // 尝试刷新令牌
      const refreshed = await refreshToken()
      
      if (refreshed) {
        // 使用新令牌重试请求
        const newAccessToken = localStorage.getItem('access_token')
        config.headers.Authorization = `Bearer ${newAccessToken}`
        return fetch(url, config)
      } else {
        // 刷新失败，清除存储的令牌并重定向到登录页
        clearAuth()
        window.location.href = '/login'
        throw new Error('登录已过期，请重新登录')
      }
    }
    
    return response
  } catch (error) {
    console.error('请求错误:', error)
    throw error
  }
}

// 刷新令牌
const refreshToken = async () => {
  const refreshToken = localStorage.getItem('refresh_token')
  
  if (!refreshToken) {
    return false
  }
  
  try {
    const response = await fetch('/api/auth/refresh-token/', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        refresh: refreshToken
      })
    })
    
    if (!response.ok) {
      throw new Error('刷新令牌失败')
    }
    
    const data = await response.json()
    
    // 更新存储的令牌
    localStorage.setItem('access_token', data.access)
    
    return true
  } catch (error) {
    console.error('刷新令牌错误:', error)
    clearAuth()
    return false
  }
}

// 清除认证信息
const clearAuth = () => {
  localStorage.removeItem('access_token')
  localStorage.removeItem('refresh_token')
  localStorage.removeItem('user')
}

export default request 